package com.ycxy.school.express.service.impl;

import com.ycxy.school.express.ex.ServiceException;
import com.ycxy.school.express.mapper.AddressMapper;
import com.ycxy.school.express.pojo.dto.AddressAddNewDTO;
import com.ycxy.school.express.pojo.dto.AddressUpdateDTO;
import com.ycxy.school.express.pojo.entity.Address;
import com.ycxy.school.express.pojo.vo.AddressListItemVO;
import com.ycxy.school.express.pojo.vo.AddressStandardVO;
import com.ycxy.school.express.pojo.vo.RoleListItemVO;
import com.ycxy.school.express.security.LoginPrincipal;
import com.ycxy.school.express.service.IAddressService;
import com.ycxy.school.express.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author jayLuo
 * @Date 2023/1/5 19:44
 * @PackageName:com.ycxy.school.express.service.impl
 * @ClassName: AddressServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Service
@Slf4j
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public void addNew(AddressAddNewDTO addressAddNewDTO) {
        log.debug("开始处理【添加地址】的业务，参数：{}", addressAddNewDTO);

        log.debug("即将检查地址是否被占用……");
        {
            // 从参数对象中获取username
            String address = addressAddNewDTO.getAddress();
            Long userId = getUserId();
            // 调用addressMapper的countByAddress()方法执行统计查询
            int count = addressMapper.countByAddress(address,userId);
            // 判断统计结果是否不等于0
            if (count != 0) {
                // 是：抛出异常
                String message = "添加地址失败，地址【" + address + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        //创建Address对象
        Address address = new Address();
        LocalDateTime now = LocalDateTime.now();
        BeanUtils.copyProperties(addressAddNewDTO,address);
        String addAddress= address.getProvince()+address.getCity()
                +address.getCounty()+address.getAddressDetail();
        address.setCreateData(now);
        address.setUserId(getUserId());
        address.setAddress(addAddress);
        //调用AddressMapper的insert方法
        int rows = addressMapper.insert(address);
        // 判断插入数据的结果是否符合预期
        if (rows != 1) {
            String message = "添加地址失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除地址】的业务，参数：{}", id);
        // 调用addressMapper的int deleteById(Long id)执行删除，并获取返回的行数
        int rows = addressMapper.deleteById(id);
        // 判断返回的行数是否不为1
        if (rows != 1) {
            // 是：抛出异常（ERR_DELETE：服务器忙）
            String message = "删除地址失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void update(Long id, AddressUpdateDTO addressUpdateDTO) {
        log.debug("开始处理【更新地址】的业务, 参数ID: {},新数据: {}",id,addressUpdateDTO);

        Address address = new Address();
        LocalDateTime now = LocalDateTime.now();
        BeanUtils.copyProperties(addressUpdateDTO,address);
        String addAddress= address.getProvince()+address.getCity()
                +address.getCounty()+address.getAddressDetail();
        address.setId(id);
        address.setAddress(addAddress);
        address.setModifiedData(now);

        // 调用addressMapper的int updateById(Address address)执行修改，并获取返回的行数
        int rows = addressMapper.updateById(address);
        // 判断返回的行数是否不为1
        if (rows != 1) {
            // 是：抛出异常（ERR_DELETE：服务器忙）
            String message = "修改地址失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }

    }

    @Override
    public List<AddressListItemVO> list() {
        log.debug("开始处理【根据用户id查询地址列表】的业务");
        List<AddressListItemVO> list = addressMapper.listByUserId(getUserId());
        return list;
    }

    @Override
    public AddressStandardVO getAddressDetailsById(Long id) {
        log.debug("开始处理【根据id查询地址详情】的业务");
        AddressStandardVO addressDetails = addressMapper.getAddressDetailsById(id);
        return addressDetails;
    }

    public LoginPrincipal getUserInfo(){
        // 编写获取SpringSecurity上下文的代码
        LoginPrincipal principal = (LoginPrincipal)
                SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 为了逻辑严谨,判断一下SpringSecurity上下文中信息是不是null
        if(principal == null){
            throw new ServiceException(
                    ServiceCode.ERR_UNAUTHORIZED,"您没有登录!");
        }
        return principal;
    }
    // 业务逻辑层需求中,实际上只需要用户的id
    // 我们可以再编写一个方法,从用户对象中获取id
    public Long getUserId(){
        return getUserInfo().getId();
    }

}
